import copy
import urllib
import urlparse

class Uri:
	def __init__(self, uri):
		parsed = urlparse.urlparse(uri, 'http')
		self.scheme = parsed.scheme
		self.authority = parsed.netloc
		self.path = parsed.path
		self.params = parsed.params
		self.query = urlparse.parse_qs(parsed.query, True)
		self.fragment = parsed.fragment

	def __repr__(self):
		return urlparse.urlunparse((
			self.scheme,
			self.authority,
			self.path,
			self.params,
			urllib.urlencode(self.query, True),
			self.fragment
		))

	def absPath(self, *args, **kwargs):
		cpy = copy.deepcopy(self)
		cpy.path = '/' + '/'.join(map(str, args))
		if kwargs.get('returnto'):
			cpy.query = {'returnto': repr(self)}
		else:
			cpy.query = {}
		return cpy

	def relPath(self, *args, **kwargs):
		cpy = copy.deepcopy(self)
		if cpy.path[-1] == '/':
			cpy.path += '/'.join(map(str, args))
		else:
			cpy.path += '/' + '/'.join(map(str, args))

		if kwargs.get('returnto'):
			cpy.query = {'returnto': repr(self)}
		else:
			cpy.query = {}
		return cpy

	def addParams(self, **kwargs):
		cpy = copy.deepcopy(self)
		cpy.query = dict(cpy.query.items() + map(list, kwargs.items()))
		return cpy
